<template>
	<view class="page-146_white">
	</view>
</template>

<script setup>
	// 现在直接就是组合式api 来操作
	import {
		reactive,
		ref,
		onMounted,
		watchEffect,
		watch,
		nextTick,
		onUnmounted,

	} from 'vue';
	import {
		onLoad,
		onShow,
		onPageScroll
	} from '@dcloudio/uni-app';
	import { uuIds } from '@/utils/login.js';
	import { getProductNum } from '@/utils/commo.js';
	import initApi from '@/apis/init.js';
	import { storeToRefs } from 'pinia';
	import { useCounterStore } from '@/store/counter.js';
	import { useUserStore } from '@/store/user.js';
	import useSendCode from '@/comApi/sendCode.js';
	import useConfirmOrder from '@/comApi/confirmOrder';
	import paramApi from '@/apis/paramApi.js';
	const isShowAgreementConfirm = ref(false);
	const uuIdsInit = uuIds();
	const {
		token,
		userInfo,
		orderNo2533,
		orderTime2533
	} = storeToRefs(useUserStore());
	/* dialog */
	const popupPro = ref();
	const twoSure = ref();
	const successRef = ref();
	/* 表单 */
	const formData = reactive({
		mobile: '',
		smsCode: null,
		orderNo: null,
		channelCode: '',
		productCode: '',
		allChecked: false,
		agreeType: 1,
		showHeight: 0,
		url: '',
		timer: '',
		timeS: 0
	});
	const { sendCode, isSend, isTimer, isNum } = useSendCode(formData);
	const { confirmOrder } = useConfirmOrder(formData);
	const { formatPhone } = storeToRefs(useCounterStore());


	const confirmOrderBtn = async () => {
		try {
			// 二次确认
			// const isOkMobile = /^1[3-9][0-9]\d{8}$/.test(formData.mobile);
			// if (!isOkMobile) return uni.utils.toast('手机号不正确');

			//  接下来 就是 下单 然后登录 然后跳转
			const arr = {
				productCode: 'LH2533',
				channelCode: formData.channelCode,
				mobile: formData.mobile,
				param: paramApi.getParam() || formData.url,
				orderType: 1,
				paymentMethod: 2,
				uuid: uuIdsInit,
				environmentCode: '12',
				scenarioCode: '7'
			};
			const loginRes = await initApi.authRegister({ mobile: formData.mobile, });
			if (loginRes.code == 20000) {
				uni.setStorageSync('token', loginRes.data.accessToken);
				userInfo.value.token = loginRes.data.accessToken;
				userInfo.value.mobile = loginRes.data.mobile;
				userInfo.value.username = loginRes.data.username;
				userInfo.value.info = loginRes.data;
				token.value = loginRes.data.accessToken;
			} else {
				window.location.href =
					'https://flycard.cscmgg.com/pages/H5-mobile/stock/coce2844_PrlQYh?channelCode=uxQEVDxp&partyId=1';
				return uni.utils.toast(loginRes.message);
			}
			const res = await initApi.associateMemberSign(arr); // 签约 orderNo
			if (res.code != 20000) {
				window.location.href =
					'https://flycard.cscmgg.com/pages/H5-mobile/stock/coce2844_PrlQYh?channelCode=uxQEVDxp&partyId=1';
				return uni.utils.toast(res.message);
			};
			if (res.code == 20000) {
				// 存数据
				orderNo2533.value = res.data.orderNo;
				orderTime2533.value = getTime();
				handleJumpPaySign(res.data);
				console.log(res.data);
			} else {
				window.location.href =
					'https://flycard.cscmgg.com/pages/H5-mobile/stock/coce2844_PrlQYh?channelCode=uxQEVDxp&partyId=1';
			}
		} catch (error) {
			//TODO handle the exception
			window.location.href =
				'https://flycard.cscmgg.com/pages/H5-mobile/stock/coce2844_PrlQYh?channelCode=uxQEVDxp&partyId=1';
			console.log(error, 'confirmOrderBtn');
		}


	};
	/* 微信签约 */
	const handleJumpPaySign = async query => {
		const device = await uni.getSystemInfo();
		let ua = navigator.userAgent.toLowerCase();
		if (ua.includes('micromessenger')) {
			if (device.osName === 'android') {
				let url = 'https://api.zzqz2024.com/api/associateMember/command/evokeBroswer?redirect=' +
					encodeURIComponent(
						`https://m.fengxingss.com/pages/lhhy/midPage?url=${query.extInfo?.alipaySignUrl}&orderNo=${query.orderNo}&orderTime=${getTime()}`
					);
				window.location.href = url;
			} else if (device.osName === 'ios') {
				window.location.href = 'safari-' + encodeURIComponent(
					`https://m.fengxingss.com/pages/lhhy/midPage?url=${query.extInfo?.alipaySignUrl}`);
			}
		} else {
			window.location.href = query.extInfo?.alipaySignUrl;
		}
	};

	const timer = async () => {


		const res = await initApi.orderDetail({ orderNo: orderNo2533.value });
		if (res.code == 20000) {
			orderNo2533.value = '';
			orderTime2533.value = '';
			/*   
			  "1": "初始",
			  "2": "签约",
			  "3": "解约",
			  "4": "退款"
			*/
			if (res.data.orderStatus == 2) {
				window.location.href =
					'https://flycard.cscmgg.com/pages/H5-mobile/stock/coce2844_PrlQYh?channelCode=uxQEVDxp&partyId=1&status=1';
			} else {
				window.location.href =
					'https://flycard.cscmgg.com/pages/H5-mobile/stock/coce2844_PrlQYh?channelCode=uxQEVDxp&partyId=1';
			}
		} else {
			window.location.href =
				'https://flycard.cscmgg.com/pages/H5-mobile/stock/coce2844_PrlQYh?channelCode=uxQEVDxp&partyId=1';
			orderNo2533.value = '';
			orderTime2533.value = '';
		}

	};
	const getTime = () => {
		return new Date().getTime();
	};
	const hasMore15s = lastOrderTime => {
		if (!lastOrderTime) {
			return false;
		}
		const currentTime = getTime();
		return (currentTime - lastOrderTime) > 15 * 1000; // 5 minutes in milliseconds
	};

	onLoad(query => {

		const oMeta = document.createElement('meta');
		oMeta.name = 'referrer';
		oMeta.content = 'no-referrer-when-downgrade';
		document.getElementsByTagName('head')[0].appendChild(oMeta);

		console.log('进入页面', query);
		formData.url = location.href;
		formData.channelCode = query.a;
		formData.mobile = query.mobile;
		paramApi.initData(query);
		if (!query.a || !query.mobile) {
			uni.reLaunch({ url: '/pages/clb/404' });
		}
		// 1 第一次进来 有什么电话号码 
		let intervalId2533 = setInterval(() => {
			formData.timeS++;
			// 这个直接就是 7s 过后查询
			if (formData.timeS >= 5) {
				clearInterval(intervalId2533); // 清除定时器
				timer();
				return;
			}
		}, 1000);
		if (orderTime2533.value && orderNo2533.value) {
			// 补充一个逻辑 上次没有完成 然后这次又进来 直接清楚数据 重新下单
			if (hasMore15s(orderTime2533.value)) {
				orderTime2533.value = ''; 
				 orderNo2533.value = '';
				confirmOrderBtn();
				return;
			}
			return;
		} else {
			nextTick(async () => {
				await confirmOrderBtn();
				await getProductNum(formData.channelCode, 'LH2535', uuIdsInit);
				return;
			});
		}

	});

	onUnmounted(() => {
		if (formData.timer) {
			clearInterval(formData.timer);
		}
	});
</script>

<style lang="scss" scoped>
	.page-146_white {
		width: 750rpx;
		margin: 0 auto;
		background-color: #fff;
	}
</style>
<style>
	page {
		height: 100%;
		width: 750rpx;
		margin: 0 auto;
	}

	/* 用户先登录  */
</style>